package com.wisdom.disposition.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.wisdom.disposition.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Description:验证码
 * User: 11951
 * Date: 2025-03-14
 * Time: 15:06
 */
@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    private static final long VALID_MILLIS_TIME =60 * 1000 ;
    @Autowired
    private CaptchaProperties captchaProperties;
    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpSession session,HttpServletResponse response) {
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(),
                captchaProperties.getHeight());
            response.setContentType("image/jpeg");
            //禁止使用缓存
            response.setHeader("Pragma","No-cache");
        try{
            //图片验证码写出，可以写到文件，也可以写出到流
            //输出到页面
            lineCaptcha.write(response.getOutputStream());
//            存储到session
            session.setAttribute(captchaProperties.getSession().getKey(),
                    lineCaptcha.getCode());
            session.setAttribute(captchaProperties.getSession().getDate(),
                    new Date());
            //打印日志
            System.out.println("生成的验证码：" + lineCaptcha.getCode());
            response.getOutputStream().close();
        }catch (IOException e){
            e.printStackTrace();

        }
    }
    /*
    * 检验验证码
    * */
    @RequestMapping("/check")
    public boolean checkHomeCaptcha(String captcha,HttpSession session){
        if(!StringUtils.hasLength(captcha)){
            return false;
        }
        String savedCaptcha = (String) session.getAttribute(captchaProperties.getSession().getKey());
        Date sessionDate= (Date) session.getAttribute(captchaProperties.getSession().getDate());
        if(captcha.equalsIgnoreCase(savedCaptcha)){
             if(sessionDate == null
                || System.currentTimeMillis() - sessionDate.getTime()<
             VALID_MILLIS_TIME){
                return true;
            }
            return false;
        }
        return false;
    }
}
